﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Linq;
using System.Web.DynamicData;
using System.Web.Routing;
using NotAClue.ComponentModel.DataAnnotations;
using NotAClue;
using NotAClue.Web.DynamicData;
using System.Reflection;

namespace DD_Extensions
{
    public class Global : System.Web.HttpApplication
    {
        public const string CURRENT_PAGER_PAGE = "_CurrentPagerPage";
        public const string ALLOW_PAGING = "_AllowPaging";
        public const string MULTI_COLUMN_SEARCH = "_MultiColumnSearch";
        public static List<String> AdminGroups { get; private set; }

        private const int INT_ASPxPivotGrid1Width = 839;
        private const int INT_FieldWidth = 356;

        public static String ApplicationVersion { get; set; }

        public static int ASPxPivotGrid1Width
        {
            get { return INT_ASPxPivotGrid1Width; }
        }

        public static int FieldWidth
        {
            get { return INT_FieldWidth; }
        }

        // instantiate custom meta model
        private static MetaModel s_defaultModel = new SecureMetaModel()
            {
                ShowChildrenColumns = false,
                EnableChildrenNavigation = true,
                EnableForeighKeyNavigation = true,
            };

        public static MetaModel DefaultModel
        {
            get { return s_defaultModel; }
        }

        void Application_Start(object sender, EventArgs e)
        {
            // setup default model
            // display version info
            Assembly assm = Assembly.GetExecutingAssembly();
            ApplicationVersion = assm.FullName.Split(',')[1].Trim();

            // set global CSS class for required field
            FieldTemplateExtensionMethods.RequiredCssClass = "DDRequired";

            //// add auto secured columns
            //var denyRead = new SecureColumnAttribute(ColumnActions.DenyRead, "ORMP Administrator", "Records Manager", "guest") { ShowFilter = true };
            //var hideInList = new HideColumnInAttribute(PageTemplate.List | PageTemplate.DetailsList | PageTemplate.Insert);
            //var filterAttribute = new FilterAttribute()
            //    {
            //        HiddenForRoles = new String[] { "ORMP Administrator", "Records Manager", "guest" },
            //        Order = 99
            //    };
            //DefaultAttributesTypeDescriptor.AutoColumnAttributes = new Dictionary<String, List<Attribute>>()
            //    {
            //        {"IsDeleted", new List<Attribute>() {denyRead, hideInList, filterAttribute}},
            //        {"IsFrozen", new List<Attribute>() {denyRead, hideInList, filterAttribute}},
            //    };

            // add audit fields for hiding
            DefaultAttributesTypeDescriptor.AutoSaffoldFalse = new List<String>()
                {
                    "PersonCreated",
                    "TimeCreated",
                    "PersonAmended",
                    "TimeAmended",
                };

            //[FilterColumn("IsDeleted", false)]
            //var filterByColumn = new FilterColumnAttribute("IsDeleted", false);
            //[SecureTable(CombinedActions.Full, "DBA", "ORMP Administrator")]
            //[SecureTable(CombinedActions.ReadOnly, "Records Manager", "guest")]
            //var secureTable = new SecureTableAttribute(CombinedActions.Full, "DBA", "ORMP Administrator");
            //DefaultAttributesTypeDescriptor.AutoTableAttributes = new Dictionary<string, Attribute>()
            //    {
            //        //{"IsDeleted", filterByColumn},
            //        {"RecordLibrary", secureTable},
            //    };

            // add auto filters
            DefaultAttributesTypeDescriptor.AutoFilters = new Dictionary<String, String>()
                {
                    {"IsDeleted", "BooleanCheckBox"},
                    {"IsFrozen", "BooleanCheckBox"},
                    //{"AppUser", "User"},
                };

            //// add auto filters
            //DefaultAttributesTypeDescriptor.AutoFilterDefaultValue = new Dictionary<String, Object>()
            //    {
            //        {"IsDeleted", false},
            //        {"IsFrozen", false},
            //    };

            // add audit fields for hiding
            StringExtensionMethods.ReplaceableWords = new Dictionary<String, String>()
                {
                    //{"PMD", "PMD"},
                };

            // add audit fields for hiding
            StringExtensionMethods.RemovableWords = new List<String>()
                {
                    //"tbl", // remove the tbl prefix from all application tables
                };

            //// get admin groups list
            //AdminGroups = ConfigurationManager.AppSettings["AdminGroups"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();

            //// add page template mapping for Move same as DetailsList page template
            //PageTemplateExtensionMethods.PageTemplateMappings.Add("Move", PageTemplate.DetailsList);

            ////Make the Move button action have the same security level as Edit
            //SecureLinkButton.ButtonMappings["Edit"].Add("move");

            RegisterRoutes(RouteTable.Routes);
        }

        #region Not in use
        protected void Session_End(object sender, EventArgs e)
        {
        }

        protected void Application_End(object sender, EventArgs e)
        {
        }

        protected void Session_Start(object sender, EventArgs e)
        {
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
        }

        protected void Application_Error(object sender, EventArgs e)
        {
        }
        #endregion

        public static void RegisterRoutes(RouteCollection routes)
        {
            #region Register Meta Model
            // add AdvancedFieldTemplateFactory
            DefaultModel.FieldTemplateFactory = new SecureFieldTemplateFactory();

            // add new entity template factory that works with single files also
            DefaultModel.EntityTemplateFactory = new AdvancedEntityTemplateFactory();

            // register data model
            DefaultModel.RegisterContext(typeof(Models.DD_ExtensionsEntities),
                new ContextConfiguration()
                {
                    ScaffoldAllTables = true,
                    MetadataProviderFactory =
                        (type => new DefaultAttributesTypeDescriptionProvider(type,
                            new AssociatedMetadataTypeTypeDescriptionProvider(type)))
                });
            #endregion

            #region Routes
            //// in place of Details view for selected tables
            //routes.Add("DetailsList", new DynamicDataRoute("{table}/{action}.aspx")
            //{
            //    // add constraints
            //    Constraints = new RouteValueDictionary(new
            //    {
            //        // constrain to following actions
            //        action = "Details",
            //        // constrain to the following tables
            //        table = "Persons"
            //    }),
            //    RouteHandler = new SecureDynamicDataRouteHandler(),
            //    // use this view instead
            //    ViewName = "DetailsList",
            //    Model = DefaultModel
            //});

            //// in place of Details view for selected tables
            //routes.Add("EditList", new DynamicDataRoute("{table}/{action}.aspx")
            //{
            //    // add constraints
            //    Constraints = new RouteValueDictionary(new
            //    {
            //        // constrain to following actions
            //        action = "Edit",
            //        // constrain to the following tables
            //        table = "Persons"
            //    }),
            //    RouteHandler = new SecureDynamicDataRouteHandler(),
            //    // use this view instead
            //    ViewName = "EditList",
            //    Model = DefaultModel
            //});

            // register default route always keep default route last?
            routes.Add("Default", new DynamicDataRoute("{table}/{action}.aspx")
            {
                Constraints = new RouteValueDictionary(new
                    {
                        action = "List|Details|Edit|Insert"
                    }),
                RouteHandler = new SecureDynamicDataRouteHandler(),
                Model = DefaultModel
            });


            //Reports/{ReportId}
            routes.MapPageRoute("Reports", "Report/{ReportName}/olap.aspx", "~/Reports/olap.aspx");

            // list details routes
            //routes.Add(new DynamicDataRoute("{table}/ListDetails") {
            //    Action = PageAction.List,
            //    RouteHandler = new SecureDynamicDataRouteHandler(),
            //    ViewName = "ListDetails",
            //    Model = DefaultModel
            //});

            //routes.Add(new DynamicDataRoute("{table}/ListDetails") {
            //    Action = PageAction.Details,
            //    RouteHandler = new SecureDynamicDataRouteHandler(),
            //    ViewName = "ListDetails",
            //    Model = DefaultModel
            //});


            //routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            #endregion
        }
    }
}